import { RouteRecordRaw, createRouter, createWebHistory } from 'vue-router';
import NProgress from "nprogress"
import 'nprogress/nprogress.css'
import { useUserStore } from '@/store/modules/userStore';
import { useMenuStore } from '@/store/modules/menuStore';

//进度条配置
NProgress.configure({
    easing: 'ease', // 动画方式
    speed: 500, // 递增进度条的速度
    showSpinner: false, // 是否显示加载 icon
    trickleSpeed: 200, // 自动递增间隔
    minimum: 0.3 // 初始化时的最小百分比
})

export const router = createRouter({
    history: createWebHistory(),
    strict: true,
    routes: []

})

const staticRoutes: Array<RouteRecordRaw> = [
    {
        path: '/',
        name: 'Layout',
        redirect: '/home',
        component: () => import('@/layout/index.vue'),
        meta: {
            menuName: '首页'
        },
        children: [
            {
                path: '/home',
                name: 'home',
                component: () => import('@/views/pages/home/index.vue')
            }
        ]
    },
    {
        path: '/login',
        name: 'Login',
        component: () => import('@/views/Login.vue')
    }, {
        path: '/register',
        name: 'Register',
        component: () => import('@/views/Register.vue')
    }]

//将静态路由添加到router
staticRoutes.forEach(route => {
    router.addRoute(route)
})

// 设置路由守卫
router.beforeEach(async (to, from, next) => {

    NProgress.start()

    const userStore = useUserStore()
    const menuStore = useMenuStore()
    const token: string = userStore.token

    //如果没有token则重回登录页
    if (!token && to.name !== 'Login' && to.name !== 'Register') {
        next('/login')
        return
    } else if (to.name === 'Login') {
        //去往登录页面时,清除本地的用户数据
        userStore.resetState()
        next()
        return
    } else if (router.getRoutes().length - 1 === staticRoutes.length) {

        //若路由长度-1等于静态路由长度说明动态路由未添加，则动态请求路由
        //(router.getRoutes().length -1 是因为getRoutes返回的是平铺的数组，所以多了一条子路由长度)

        await menuStore.getMenuList()

        menuStore.routeList.forEach(route => {
            router.addRoute('Layout', route)
        })

        //添加404页面，若将404写成静态路由，则在访问动态添加的路由时会直接跳转到404页面，所以需要在动态路由添加后添加404页面
        router.addRoute({
            path: '/:pathMatch(.*)*',
            name: 'PadgeNotFond',
            component: () => import('@/views/PageNotFound.vue')
        })

        //使用next({ ...to, replace: true })来确保addRoute()时动态添加的路由已经被完全加载上去
        next({ ...to, replace: true })
        return
    }

    next()

})

router.afterEach(() => {
    NProgress.done()
})

